package com.shtel.bss.saas.tenant.service.impl;

import com.github.pagehelper.PageInfo;
import com.shtel.bss.saas.core.base.exception.ExceptionBuilder;
import com.shtel.bss.saas.core.data.common.service.DataServiceImpl;
import com.shtel.bss.saas.tenant.bo.SysUserBo;
import com.shtel.bss.saas.tenant.entity.SysUser;
import com.shtel.bss.saas.tenant.enums.SysExceptionCode;
import com.shtel.bss.saas.tenant.manager.SysUserManager;
import com.shtel.bss.saas.tenant.mapstrut.EntityDtoMapper;
import com.shtel.bss.saas.tenant.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户表服务
 *
 * @author xiezhiwei 2020-02-05 22:02
 */
@Service("SysUserService")
public class SysUserServiceImpl extends DataServiceImpl implements ISysUserService {
    @Override
    public PageInfo<SysUserBo> qrySysUserList(SysUserBo sysUserBo, int pageNum, int pageSize) {
        return EntityDtoMapper.INSTANCE.toSysUserBoPageInfo(SysUserManager.selectEntity(EntityDtoMapper.INSTANCE.toSysUser(sysUserBo), pageNum, pageSize));
    }

    @Override
    public SysUserBo qrySysUser(SysUserBo sysUserBo) {
        return EntityDtoMapper.INSTANCE.toSysUserBo(SysUserManager.selectOne(EntityDtoMapper.INSTANCE.toSysUser(sysUserBo)));
    }

    @Override
    public void saveSysUser(SysUserBo sysUserBo) {
        if(StringUtils.isEmpty(sysUserBo.getAccount())){
            throw ExceptionBuilder.paramsException(SysExceptionCode.PARAM_IS_NULL,"用户名为空");
        }
        if(StringUtils.isEmpty(sysUserBo.getPassword())){
            throw ExceptionBuilder.paramsException(SysExceptionCode.PARAM_IS_NULL,"密码为空");
        }
        if(SysUserManager.selectByAccount(sysUserBo.getAccount()) != null){
            throw ExceptionBuilder.paramsException(SysExceptionCode.ACCOUNT_IS_EXISTS,sysUserBo.getAccount());
        }
        SysUserManager.saveEntity(EntityDtoMapper.INSTANCE.toSysUser(sysUserBo));
    }

    @Override
    public void updateSysUser(SysUserBo sysUserBo) {
        SysUserManager.updateEntity(EntityDtoMapper.INSTANCE.toSysUser(sysUserBo));
    }

    @Override
    public void removeSysUser(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setIsDelete((byte) 1);
        SysUserManager.updateEntity(sysUser);
    }

    @Override
    public SysUserBo login(String account,String password) {
        SysUser sysUser = SysUserManager.selectByAccount(account);
        if(sysUser == null){
            throw ExceptionBuilder.BusiException(SysExceptionCode.ACCOUNT_NOT_FIND,account);
        }
        if(!password.equals(sysUser.getPassword())){
            throw ExceptionBuilder.BusiException(SysExceptionCode.PASSWORD_IS_ERROR,account,password);
        }
        return EntityDtoMapper.INSTANCE.toSysUserBo(sysUser);
    }
}